<?php

namespace App\Logic\Auth\Form;

use App\Core\BaseForm;
use App\Core\Exception\DefaultException;
use App\Model\Auth\RoleModel;

class RoleStateSaveForm extends BaseForm{
    
    public $id;

    public function rules(){
        return [
            'id'    => ['required|notEmpty', '角色id', '角色id错误'],
        ];
    }

    protected $_info;
    
    /**
     * 校验提交数据
     * @return bool
     * @throws DefaultException
     * @throws \EasySwoole\Validate\Exception\Runtime
     */
    public function validate(){
        //生成验证器，方法自动读取rules方法返回的值数据
        $validate = $this->createValidator();

        if(!($check = $validate->validate($this->getAttributes()))){
            throw new DefaultException($validate->getError()->__toString(), 600);
        }
        
        if(empty($this->getInfo())){
            throw new DefaultException('不存在记录');
        }

        if ( $this->getInfo()->is_action == RoleModel::DISABLED ){
            throw new DefaultException('该角色不允许编辑');
        }

        return true;
    }
    
    /**
     * 保存数据
     * @return \App\Core\Output
     * @throws DefaultException
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \EasySwoole\Validate\Exception\Runtime
     * @throws \Throwable
     */
    public function saveData(){
        $this->validate();

        $data = [];
        $data['state'] = $this->_info->state == RoleModel::DISABLED ? RoleModel::ENABLED : RoleModel::DISABLED;

        RoleModel::updateData($data, ['id' => $this->id]);
        
        return $this->success(['id' => $this->id ]);
    }
    
    /**
     * 获取详情
     * @return \App\Core\BaseModel|array|bool|\EasySwoole\ORM\AbstractModel|\EasySwoole\ORM\Db\Cursor|\EasySwoole\ORM\Db\CursorInterface|null
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     */
    public function getInfo(){
        if($this->_info === null){
            $this->_info = RoleModel::getOne(['id' => $this->id]);
        }
        return $this->_info;
    }
    
}